package com.jzr.bedside.db1.service.Impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzr.bedside.db1.mapper.MyDeviceMapper;
import com.jzr.bedside.db1.mapper.TBedMapper;
import com.jzr.bedside.db1.mapper.TDeviceMapper;
import com.jzr.bedside.db1.model.TBed;
import com.jzr.bedside.db1.model.TDevice;
import com.jzr.bedside.db1.service.TDeviceService;
import com.jzr.common.util.U;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TDeviceServiceImpl extends ServiceImpl<TDeviceMapper,TDevice> implements TDeviceService {
    @Autowired
    private MyDeviceMapper deviceMapper;

    @Autowired
    private TBedMapper bedMapper;

    public List<Integer> getIdList(@Param(Constants.WRAPPER) Wrapper wrapper){
        return baseMapper.getIdList(wrapper);
    }
    public Integer getId(@Param(Constants.WRAPPER) Wrapper wrapper){
        List<Integer> list = getIdList(wrapper);
        return list == null || list.size() <= 0 ? null : list.get(0);
    }

    @Override
    @Transactional
    public Integer bindToBed(TDevice record) throws Exception{
        int count = 0;

        if(U.isBlank(record.getDeviceNo())){
            throw new Exception("DeviceNo不能为空");
        }
        if(U.isBlank(record.getRegisterBed())){
            throw new Exception("RegisterBed不能为空");
        }

        //取消其他card的绑定
        if(record.getRegisterBed() != null){
            deviceMapper.cancelRegisterBed(record.getRegisterBed());
        }
        if(record.getDeviceIp() != null){
            deviceMapper.cancelDeviceIp(record.getDeviceIp());
        }

        //更新或插入device
        Integer tmpId = getId(new QueryWrapper<TDevice>().eq(TDevice.DeviceNo_,record.getDeviceNo()));
        if(tmpId == null){
            if(record.getDeviceType() == null){
                record.setDeviceType(1);
            }
            count += deviceMapper.insert(record);
        }else{
            deviceMapper.cancelBindBed(tmpId);
            record.setId(tmpId);
            count += deviceMapper.updateById(record);
        }

        //更新bed
        TBed tBed = new TBed();
        tBed.setId(record.getRegisterBed());
        tBed.setBedCardId(record.getId());
        count += bedMapper.updateById(tBed);

        return count;
    }
}
